package com.strongbj.iot.devices.zebra.fx7500.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mot.rfid.api3.DISCONNECTION_EVENT_TYPE;
import com.mot.rfid.api3.RfidStatusEvents;
import com.mot.rfid.api3.STATUS_EVENT_TYPE;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.iot.devices.zebra.fx7500.service.Fx7500Client;

import io.netty.channel.ChannelHandlerContext;

/**
 * 断开连接的处理
 * @author yuzhantao
 *
 */
public class DisconnectionHandle implements IMessageHandle<RfidStatusEvents,Object> {
	private static Logger logger = LogManager.getLogger(DisconnectionHandle.class.getName());
	private Fx7500Client client;
	
	public DisconnectionHandle(Fx7500Client client){
		this.client=client;
	}
	
	@Override
	public boolean isHandle(RfidStatusEvents t) {
		STATUS_EVENT_TYPE statusType = t.StatusEventData.getStatusEventType();
		if(statusType == STATUS_EVENT_TYPE.DISCONNECTION_EVENT){
			return true;
		}else{
			return false;
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public Object handle(ChannelHandlerContext ctx, RfidStatusEvents t) {
		String disconnectionEventData = "";
		if (t.StatusEventData.DisconnectionEventData
				.getDisconnectionEvent().READER_INITIATED_DISCONNECTION == DISCONNECTION_EVENT_TYPE.READER_INITIATED_DISCONNECTION)
			disconnectionEventData = "Reader Initiated Disconnection";
		else if ((t.StatusEventData.DisconnectionEventData
				.getDisconnectionEvent().CONNECTION_LOST == DISCONNECTION_EVENT_TYPE.CONNECTION_LOST))
			disconnectionEventData = "Connection Lost";
		else if ((t.StatusEventData.DisconnectionEventData
				.getDisconnectionEvent().READER_EXCEPTION == DISCONNECTION_EVENT_TYPE.READER_EXCEPTION))
			disconnectionEventData = "Reader Exception";
		
		logger.info("检测到Fx7500设备断开事件,IP:({})  断开原因:({})。",client.hostName, disconnectionEventData);
		try{
			this.client.disconnectReader();
		}catch(Exception e){
			logger.error("自动断开Fx7500设备异常:{}", e.getMessage());
		}
		return null;
	}

}